import { defineStore } from 'pinia'
import { getUserList, getUserDetail, createUser, updateUser, deleteUser } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    userList: [],
    userDetail: {},
    loading: false,
    total: 0
  }),

  actions: {
    // 获取用户列表
    async fetchUserList(params) {
      this.loading = true
      try {
        const response = await getUserList(params)
        this.userList = response.data
        this.total = response.total
        return response
      } catch (error) {
        console.error('获取用户列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取用户详情
    async fetchUserDetail(id) {
      this.loading = true
      try {
        const response = await getUserDetail(id)
        this.userDetail = response.data
        return response
      } catch (error) {
        console.error('获取用户详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建用户
    async createUser(data) {
      try {
        const response = await createUser(data)
        // 如果当前在用户列表页，重新获取列表
        if (this.userList.length > 0) {
          await this.fetchUserList({})
        }
        return response
      } catch (error) {
        console.error('创建用户失败:', error)
        throw error
      }
    },

    // 更新用户
    async updateUser(id, data) {
      try {
        const response = await updateUser(id, data)
        // 更新用户列表中的数据
        const index = this.userList.findIndex(user => user.id === id)
        if (index !== -1) {
          this.userList[index] = { ...this.userList[index], ...data }
        }
        // 如果是当前详情页的用户，也更新详情数据
        if (this.userDetail.id === id) {
          this.userDetail = { ...this.userDetail, ...data }
        }
        return response
      } catch (error) {
        console.error('更新用户失败:', error)
        throw error
      }
    },

    // 删除用户
    async deleteUser(id) {
      try {
        const response = await deleteUser(id)
        // 从用户列表中移除
        this.userList = this.userList.filter(user => user.id !== id)
        this.total--
        return response
      } catch (error) {
        console.error('删除用户失败:', error)
        throw error
      }
    }
  }
})